# -*- coding: utf-8 -*-
from software.models import DuanInfo, PushOther
from user.models import User
import pdb, json
from software.views.view_download import download
from conf.sysConfig import config

ifUseFastDFS = config["isUseFastDFS"]


class FindRelateDuan():
    def __init__(self, cpuType):
        self.nodes = []
        self.is_leaf = False
        # self.cpuType = cpuType
        # if cpuType == "0":
        #     self.CPU = "02"
        # elif cpuType == "1":
        #     self.CPU = "12"
        # elif cpuType == "2":
        #     self.CPU = "2"
        # else:
        #     pass

    # relatedId

    def find_duan(self, relateId, id):
        relateList = json.loads(relateId)
        self.nodes.append(id)
        if len(relateList) == 0:
            return self.nodes
        else:
            for pushItem in relateList:
                relateItem = DuanInfo.objects.filter(
                    duanPrefix=pushItem['SEGPREFIX'],
                    isLatest=True
                    # duanName=pushItem['SEGNAME'],
                    # duanVersion=pushItem['SEGVERSION'],
                ).order_by("-createTime")
                if relateItem.exists():
                    ra = relateItem[0]
                    # tmp = self.find_duan(ra.realteId, ra.id)
                    # self.nodes.append(ra.id)
                    self.find_duan(ra.realteId, ra.id)
        return self.nodes

    def findUrlById(self, idList):
        infoList = []
        for id in idList:
            duanItem = DuanInfo.objects.filter(
                pk=id
            )
            if duanItem.exists():
                di = duanItem[0]

                push = PushOther.objects.create(
                    duan=di,
                )
                if ifUseFastDFS:
                    info = {
                        "urlString": "http://" +
                                     config["FastDFSIP"] +
                                     ":" +
                                     config["FastDFSPort"] +
                                     "/" +
                                     download(di.file.fileName, "file", di.file.filePath)[1],
                        "fileName": di.file.fileName,
                        "id": push.id
                    }
                else:
                    info = {
                        "urlString": "http://" +
                                     config["ownIp"] +
                                     ":" +
                                     config["ownPort"] +
                                     "/" +
                                     download(di.file.fileName, "file", di.file.filePath)[1],
                        "fileName": di.file.fileName,
                        "id": push.id
                    }

                infoList.append(info)
        return infoList
